package com.fuhailiu.opengl.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;

import com.fuhailiu.opengl.config.ItemDataManager;
import com.fuhailiu.opengl.renders.AbsRender;
import com.fuhailiu.opengl.utils.LogUtil;

@SuppressLint("ViewConstructor")
public class MGLSurfaceView extends GLSurfaceView {

	private final String TAG = getClass().getSimpleName();

	private AbsRender mRender;

	public MGLSurfaceView(Context context, int renderId) {
		super(context);

		setEGLContextClientVersion(2);

		mRender = ItemDataManager.getRenderById(context, renderId);
		setRenderer(mRender);

		setRenderMode(mRender.getRenderMode());

		getHolder().addCallback(new Callback() {

			@Override
			public void surfaceCreated(SurfaceHolder holder) {
				LogUtil.LogD(TAG, "surfaceCreated   <---");
				LogUtil.LogD(TAG, "surfaceCreated   --->");
			}

			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
				LogUtil.LogD(TAG, "surfaceChanged   <---");
				LogUtil.LogD(TAG, "surfaceChanged   format = " + format + ", width = " + width + ", height = " + height);
				LogUtil.LogD(TAG, "surfaceChanged   --->");
			}

			@Override
			public void surfaceDestroyed(final SurfaceHolder holder) {
				LogUtil.LogD(TAG, "surfaceDestroyed   <---");
				postToGLThread(new Runnable() {
					@Override
					public void run() {
						mRender.onSurfaceDestroyed(holder);
					}
				});

				LogUtil.LogD(TAG, "surfaceDestroyed   --->");
			}
		});
	}

	public AbsRender getRender() {
		return mRender;
	}

	@Override
	public boolean onTouchEvent(final MotionEvent event) {
		postToGLThread(new Runnable() {
			@Override
			public void run() {
				mRender.onTouchEvent(event);
			}
		});

		return true;
	}

	private void postToGLThread(Runnable run) {
		MGLSurfaceView.this.queueEvent(run);
	}

}
